package com.j.comet;

import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * comet 简单实例，定时想 hello频道 发送剩余内存
 * Created by zhuangjianhui_91 on 2015/10/29.
 */
public class HelloCometListener implements ServletContextListener {

	private static final String CHANNEL = "hello";

	public void contextInitialized(ServletContextEvent arg0) {
		CometContext cc = CometContext.getInstance();
		//注册应用的channel
		cc.registChannel(CHANNEL);
		Thread helloAppModule = new Thread(new HelloAppModule(), "Sender App Module");
		helloAppModule.setDaemon(true);
		helloAppModule.start();
	}

	class HelloAppModule implements Runnable {
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				CometEngine engine = CometContext.getInstance().getEngine();
				engine.sendToAll(CHANNEL, Runtime.getRuntime().freeMemory() / 1024);
			}
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
	}
}
